<template>
  <div id="allocatedManage">
    <!--上部搜索条件组件-->
    <topSearch
      ref="topSearch"
      :form-inline="formInline"
      @toSearch="searchList"
      :searchParams="searchParams"
    ></topSearch>
    <!-- 操作按钮 -->
    <div class="table-conBtn">
      <el-button type="warning" @click="importBtn">
        导入用户
      </el-button>
      <el-button type="warning" @click="batchAward" :loading="batchLoading">
        批量确认
      </el-button>
      <freshCom @searchList="searchList"></freshCom>
    </div>
    <!-- 表格部分-->
    <el-table
      v-loading="confirLoading"
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="490"
      ref="table"
      @select="selectCheckbox"
      @select-all="selectAllCheckbox"
    >
      <el-table-column
        type="selection"
        :selectable="selectAble"
        width="50"
      ></el-table-column>
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          {{
            scope.$index
              | filterPage(searchParams.pageNum, searchParams.pageSize)
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="导入名单时间"
        min-width="80"
      ></el-table-column>
      <el-table-column
        prop="setTime"
        label="确认发放时间"
        min-width="80"
      ></el-table-column>
      <el-table-column
        prop="dpAccount"
        label="大鹏号"
        min-width="120"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="college.name"
        label="赠送学院"
        min-width="140"
      ></el-table-column>
      <el-table-column prop="servicePeriod" label="赠送服务期" min-width="80">
        <template slot-scope="scope">
          <span> {{ scope.row.servicePeriod || 0 }} 个月 </span>
        </template>
      </el-table-column>
      <el-table-column label="是否确认" min-width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 'CONFIRMED'" class="tag-span"
            >已确认</span
          >
          <span v-if="scope.row.state == 'UNCONFIRMED'" class="tag-span"
            >未确认</span
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            @click="confirmBtn(scope.row)"
            :type="scope.row.state == 'CONFIRMED' ? 'info' : 'text'"
            :disabled="scope.row.state == 'CONFIRMED'"
          >
          <span>确认</span>
          </el-button>
          <span v-if="scope.row.state == 'UNCONFIRMED'">|</span>
          <el-button
            type="text"
            @click="deleteBtn(scope.row)"
            v-if="scope.row.state == 'UNCONFIRMED'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-全局组件-->
    <pageCom
      :searchParams="searchParams"
      :total="total"
      @searchList="searchList"
    ></pageCom>
    <!--编辑角色dialog -->
    <dialogEdit
      v-if="dialogData.isShow"
      :dialog-data="dialogData"
      @refresh="refresh"
    ></dialogEdit>
    <!-- 导入弹窗 -->
    <importDialog
      v-if="importDialogData.isShow"
      :dialog-data="importDialogData"
      @refresh="searchList"
      @showError="showError"
    ></importDialog>
    <!-- 导入失败弹窗 -->
    <errorDialog
      v-if="errorDialogData.isShow"
      :dialog-data="errorDialogData"
      from="downErrorData"
    ></errorDialog>
    <div v-if="showBtn" class="btn-box">
      <el-button plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button type="primary" @click="nextLab('prizeSetting')">
        上一步
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  getAllocatedMange,
  batchAwardAll,
  importUrl,
  downUrl,
  batchOrder,
  importUserUrl,
  deleteOrder,
  confirmOrder,
  extensionServer,
  DownloadingTemplate
} from '@component/activeManagement/common/js/lableApi' // 导入公用方法
import topSearch from '@component/activeManagement/common/templatePage/grantUser/topSearch' // 上部搜索条件
import dialogEdit from '@component/activeManagement/common/templatePage/grantUser/dialogEdit' //编辑
import importDialog from '@common/importDialog' // 导入弹窗
import errorDialog from '@common/errorDialog' // 导入失败弹窗
import { clearTagMixins } from '@/mixins/clearTag'
export default {
  name: 'allocatedManage',
  msg: '发奖管理',
  mixins: [clearTagMixins],
  components: {
    topSearch,
    dialogEdit,
    importDialog,
    errorDialog
  },
  props: ['type', 'backPage'],
  data() {
    return {
      confirLoading:false,
      batchLoading:false,
      ids: [],
      isSave: false,
      loading: false,
      total: 0,
      tableData: [], // table内容
      formInline: {
        dpAccount: '', // 用户名称
        confirm: '', //是否确定
        dateType: '', //搜索时间类型
        endTime: '', //结束时间
        startTime: '', //开始时间
        categoryId: '',
        timeType: 'CONFIRM',
        state: ''
      },
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      // 选择框选中的数据
      multipleSelection: [],
      // 传递给编辑弹框的数据
      dialogData: {
        isShow: false, // 控制弹框显示
        params: '' // 参数
      },
      // 传递给导入弹框的数据
      importDialogData: {
        title: '添加用户',
        isShow: false, // 控制弹框显示
        params: '' // 参数
      },
      // 导入失败弹框的数据
      errorDialogData: {
        isShow: false, // 控制弹框显示
        warningText: '' // 参数
      }
    }
  },
  watch: {
    '$route.path': 'getPrizeId'
  },
  computed: {
    showBtn() {
      //是否显示保存按钮
      return this.type === 'add' || this.type === 'edit'
    }
  },
  mounted() {
    this.searchList()
  },
  methods: {
    // 表单中全选事件
    selectAllCheckbox(selection) {
      this.ids = selection.map((item) => {
        return item.id
      })
    },
    // 表单中单个选中事件
    selectCheckbox(selection, row) {
      this.ids = selection.map((item) => {
        return item.id
      })
    },
    // 表单中的删除时间
    deleteBtn(val) {
      let id = val.id
      deleteOrder(
        id,
        (res) => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$refs['table'].clearSelection()
          this.searchList()
        },
        (err) => {
          // this.$message({
          //   message:'删除失败',
          //   type:'warning'
          // })
          this.searchList()
        }
      )
    },
    confirmBtn(val) {
      this.confirLoading = true
      let id = val.id
      let params = {
        activityId: this.$route.query.id,
        isQueryString: true
      }
      confirmOrder(
        id,
        params,
        (res) => {
          this.$message({
            message: '确认成功',
            type: 'success'
          })
          this.$refs['table'].clearSelection()
          this.searchList()
          this.confirLoading = false
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warning'
          })
          this.confirLoading = false
        }
      )
    },
    getPrizeId() {
      this.id = this.$route.query.id
      let aggregationId = this.$store.state.prizeId[this.id]
      if (aggregationId) {
        this.searchList(aggregationId)
        this.$refs.topSearch.getAward(this.id)
      } else {
        this.$refs.topSearch.setDefault()
        this.tableData = []
        this.total = 0
      }
    },
    /* 获取列表 */
    searchList(aggregationId) {
      this.loading = true
      let params = { ...this.formInline, ...this.searchParams }
      delete params.createTime
      params.activityId = this.$route.query.id
      extensionServer(
        params,
        (res) => {
          this.tableData = res.rows
          this.total = res.total
        },
        (err) => {}
      )
    },
    // 编辑
    editBtn(item) {
      if (item.address) {
        this.dialogData.params = {
          state: item.state,
          name: item.address.name,
          phone: item.address.phone,
          province: item.address.province,
          city: item.address.city,
          district: item.address.district,
          particularAddress: item.address.particularAddress,
          courierCompany: item.courierCompany,
          trackingNumber: item.trackingNumber,
          prizeType: item.prizeType,
          id: item.id
        }
      } else {
        this.dialogData.params = {
          state: item.state,
          id: item.id
        }
      }

      this.dialogData.isShow = true // 显示编辑弹框
    },
    resetIsSave() {
      this.isSave = false
    },
    cancelLabel() {
      this.clearTag()
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
    },
    nextLab(labName) {
      this.$emit('changeLab', labName)
    },
    // 批量发放奖品
    batchAward() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请至少选择一条数据！')
        return
      }
        this.batchLoading = true
      let params = {
        activityId: this.$route.query.id,
        ids: this.ids
      }
      batchOrder(
        params,
        (res) => {
          this.$message({
            message: '批量确认成功',
            type: 'success'
          })
          this.$refs['table'].clearSelection()
          this.searchList()
          this.batchLoading = false
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warning'
          })
          this.$refs['table'].clearSelection()
          this.batchLoading = false
          this.searchList()
        }
      )
    },
    // 导入
    importBtn() {
      this.importDialogData.url = importUserUrl(this.$route.query.id) // 导入接口
      this.importDialogData.downUrl = DownloadingTemplate() // 下载模板接口
      this.importDialogData.isShow = true // 显示导入弹框
      this.importDialogData.noTime = 'noTime'
    },
    /* 导入失败弹窗 */
    showError(text) {
      this.errorDialogData.isShow = true // 显示导入失败弹框
      this.errorDialogData.warningText = text // 显示导入失败弹框
    },
    /* 导出 */
    exportFile(type) {
      this.$confirm('确定要导出发奖信息吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.tableData.length <= 0) {
            this.$message.error(`暂无数据，不能导出`)
            return
          }
          let aggregationId = this.$store.state.prizeId[this.id]
          let url = `/prizes/${aggregationId}/export?activityId=${this.id}`
          let params = Object.assign({}, this.formInline)
          params.pageSize = 10000000
          delete params.createTime
          this.downFile('get', url, params, '发放管理')
        })
        .catch(() => {})
    },
    // table选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /* 编辑后，刷新列表 */
    refresh() {
      this.getPrizeId()
    },
    /* 搜索 */
    toSearch() {
      this.searchParams.pageNum = 1
      // this.getPrizeId()
    },
    // 是否可被选择
    selectAble(row, index) {
      if (row.state === 'CONFIRMED') {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style lang="less">
.color_gray {
  color: gray;
}
.el-button--info.is-disabled,
.el-button--info.is-disabled:active,
.el-button--info.is-disabled:focus,
.el-button--info.is-disabled:hover {
  background: #fafafa;
  border: none;
  color: #aaaaaa;
}
</style>
